import requests
import json
import time

# X-User-Token 目前是用的李虎的账号认证码， 可以改
headers = {"X-User-Token":"756283292c03bd29dbf8a721f5ca26bc", "content-type":"application/json"}

def count_alert_history (dict_in_list):
    new_list = []
    index = 0
    for i in dict_in_list:
        i = str(i)
        new_list.append(i)
    # print(type(new_list[0]))
    new_list = list(set(new_list))
    for i in new_list:
        new_list[index] = eval(i)
        new_list[index]["count"] = dict_in_list.count(new_list[index])
        index += 1
    return new_list

def get_p1_alarm(cycle, alarm_grade):
    """
    cycle:时间周期
    alarm_grade:告警级别
    """
    keshi_turn = {
        "app_web":"前端应用研发室",
        "basic":"流量运营研发室",
        "beisheng":"倍升公司",
        "bigdata":"大数据",
        "framework":"架构室",
        "fund_deal":"资金交易组",
        "operation":"运维安全室",
        "riskone":"风控研发一室",
        "risktwo":"风控研发二室",
        "taichcao":"太潮",
        "SMY":"根节点"
    }

    etime = int(time.time())   # 结束时间
    stime = etime - cycle*24*3600  # 开始时间
    params = {"etime":etime, "limit":20000, "p":1, "nodepath":"SMY.information technology", "priorities":alarm_grade, "stime":stime, "type":"alert"}
    ret = requests.get("https://nightingale.smyoa.com/api/mon/event/his", headers=headers, params=params).text
    alert_history_list = json.loads(ret)['dat']['list']

    alert_history_list = list(filter(lambda x:"已发送" in x["status"], alert_history_list))
    index = 0
    for alert_history in alert_history_list:
        alert_history = {x: alert_history[x] for x in alert_history.keys() if x ==  "sname" or x == "node_path" or x == "endpoint"}
        alert_history_list[index] = alert_history
        index += 1
    # 计数，所有字段完全一样时去重计数
    alert_history_list = count_alert_history(alert_history_list)
    
    final_ret = {}
    for alert_history in alert_history_list:
        # print(alert_history)
        keshi = alert_history['node_path'].split('.')[2] if len(alert_history['node_path'].split('.')) >= 3 else alert_history['node_path'].split('.')[0]
        # print(alert_history, keshi)
        if keshi_turn[keshi] in final_ret:
            final_ret[keshi_turn[keshi]].append(alert_history)
        else:
            final_ret[keshi_turn[keshi]] = [alert_history]
    return final_ret


print(get_p1_alarm(1, "1"))